﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>iview example</title>
    <link rel="stylesheet" type="text/css" href="http://unpkg.com/iview/dist/styles/iview.css">
    <script type="text/javascript" src="http://vuejs.org/js/vue.min.js"></script>
    <script type="text/javascript" src="http://unpkg.com/iview/dist/iview.min.js"></script>
</head>
<body>
<div id="app">
    <row>
        <i-col span="16" offset="4">
            <h2>IP地址转二进制</h2>
            <br/> <br/>
            <row>
                <i-col span="12"><i-input v-model="value" placeholder="请输入IP地址" /></i-col>
                <i-col span="12"><i-button v-on:click="change()">开始转换</i-button></i-col>
            </row>
            <br/><br/>
            <Card>
                <p slot="title">
                    结果
                </p>
                <p>{{result}}</p>
            </Card>
        </i-col>
    </row>
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            value:'',
            result:''
        },
        methods: {
            change:function(){
                this.result = this.ipToInt(this.value);
            },
            ipToInt:function(ip){
                var REG =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
                var xH = "",result = REG.exec(ip);
                if(!result) {
                    this.$Message.error('IP地址格式错误');
                }else{
                    return this.binary(parseInt(result[1]),8) + '  ' + this.binary(parseInt(result[2]),8) + '  ' + this.binary(parseInt(result[3]),8) + '  ' + this.binary(parseInt(result[4]),8);
                }
            },
            binary:function (num, Bits) {
                var resArry = [];
                var xresArry = [];
                var i = 0;
                //除2取余
                for (; num > 0;) {
                    resArry.push(num % 2);
                    num = parseInt(num / 2);
                    i++;
                }
                //倒序排列
                for (var j = i - 1; j >= 0; j--) {
                    xresArry.push(resArry[j]);
                }
                //报错
                if (Bits < xresArry.length) {
                    console.log("控制位小于转换位数");
                }
                //补0操作
                if (Bits) {
                    for (var r = xresArry.length; r < Bits; r++) {
                        xresArry.unshift("0");
                    }
                }
                return xresArry.join().replace(/,/g, "");
            }

        }
    })
  </script>
</body>
</html>